#include "dialog_setup_plugin.h"
#include "ui_dialog_setup_plugin.h"
#include "../AvatarLibrary.h"
#include "../Program.h"

DialogSetupPlugin::DialogSetupPlugin(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DialogSetupPlugin)
{
    ui->setupUi(this);
    setFixedSize(this->width(), this->height());
    AvatarLibrary::avatar_register("__on_load_plugin", [](int, const char** params, void* userdata) {
        DialogSetupPlugin* dlg = (DialogSetupPlugin*)userdata;
        QListWidgetItem* item = new QListWidgetItem();
        item->setText(params[1]);
        item->setToolTip(params[2]);
        item->setData(Qt::UserRole + 1, params[0]);
        item->setCheckState(Program::Config.PluginUsed.contains(params[0]) ? Qt::Checked : Qt::Unchecked);
        dlg->ui->listWidgetPlugin->addItem(item);
        return 0;
    }, this);
    const QString command = "local infos = engine.plugin()\nfor k, info in ipairs(infos) do engine.execute('__on_load_plugin', info.name, info.title, info.description) end";
    AvatarLibrary::avatar_command(command);
}

DialogSetupPlugin::~DialogSetupPlugin()
{
    delete ui;
}

void DialogSetupPlugin::on_pushButtonSelectAll_clicked()
{
    Program::Config.PluginUsed.clear();
    for (int i = 0; i < ui->listWidgetPlugin->count(); i++)
    {
        ui->listWidgetPlugin->item(i)->setCheckState(Qt::Checked);
    }
}

void DialogSetupPlugin::on_pushButtonUnSelect_clicked()
{
    Program::Config.PluginUsed.clear();
    for (int i = 0; i < ui->listWidgetPlugin->count(); i++)
    {
        ui->listWidgetPlugin->item(i)->setCheckState(Qt::Unchecked);
    }
}

void DialogSetupPlugin::on_listWidgetPlugin_itemClicked(QListWidgetItem *item)
{
    if (item->checkState() == Qt::Checked) item->setCheckState(Qt::Unchecked);
    else item->setCheckState(Qt::Checked);
}

void DialogSetupPlugin::on_listWidgetPlugin_itemChanged(QListWidgetItem *item)
{
    QString name = item->data(Qt::UserRole + 1).toString();
    Program::Config.PluginUsed.removeAll(name);
    if (item->checkState() == Qt::Checked) Program::Config.PluginUsed.append(name);
}
